<template>
  <div>
    <div class="uploadimg">
      <el-upload
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :http-request="httpRequest"
        action="#"
      >
        <img v-if="value" class="avatar" :src="value" alt="">
        <i v-else class="el-icon-plus" />
      </el-upload>
      <div v-if="value" class="del" @click="delClick">
        <i class="el-icon-circle-close" />
      </div>
      <!-- 预览图标 -->
      <div v-if="value" class="show-big" @click="show = true">
        <i class="el-icon-zoom-in" />
      </div>
    </div>
    <el-progress v-if="showProgress" :width="200" :percentage="percentage" />
    <el-dialog :visible.sync="show" title="预览图片" width="600px">
      <div style="text-align: center">
        <img v-imgerror style="width: 100%" :src="value" alt="">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      COS: '',
      show: false,
      percentage: 0, // 上传的进度
      showProgress: false // 默认不显示进度条
    }
  },
  created() {
    this.COS = new COS({
      SecretId: 'AKIDvgEsIXaR4VkkV5Zw51mMZaUDhx0pRp0x',
      SecretKey: 'qW0HK2VlnbBXgbJn6BNXXWO3UgeOtAD4'
    })
  },
  methods: {
    // 删除事件
    delClick() {
      this.$confirm('您确定删除该图片吗')
        .then(() => {
          this.$emit('input', '')
        })
        .catch(() => {})
    },
    httpRequest(res) {
      // 开始上传时显示进度条
      this.showProgress = true
      this.COS.uploadFile(
        {
          Bucket: 'cw2022-11-29-1312511968' /* 填写自己的bucket，必须字段 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: res.file
            .name /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
          Body: res.file, // 上传文件对象
          SliceSize:
            1024 *
            1024 *
            5 /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */,
          onProgress: (progressData) => {
            this.percentage = +(progressData.percent * 100).toFixed(2)
            if (progressData.percent === 1) {
              this.showProgress = false
            }
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          if (err) {
            console.log('上传失败', err)
          } else {
            console.log('上传成功', data)

            this.$emit('input', 'http://' + data.Location)
          }
        }
      )
    },
    // 上传前的回调钩子
    beforeAvatarUpload(file) {
      const typeArr = ['image/jpeg', 'image/png']
      const typeBol = typeArr.includes(file.type)
      if (!typeBol) this.$message.error('请上传jpg与png图片')

      const limit1M = file.size / 1024 / 1024 < 10
      if (!limit1M) this.$message.error('只允许上传10Mb内文件')
      return typeBol && limit1M
    }
  }
}
</script>

<style lang="scss" scoped>
.uploadimg {
  position: relative;
  width: 200px;
  height: 200px;
  line-height: 0px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #ccc;
  i {
    font-size: 30px;
  }

  .avatar {
    width: 200px;
    height: 200px;
    object-fit: cover;
  }
  &:hover {
    .del {
      display: block;
    }
  }
  .del {
    position: absolute;
    top: 5px;
    right: 5px;
    font-size: 20px;
    cursor: pointer;
    display: none;
    &:hover {
      color: pink;
    }
  }
  .show-big {
    position: absolute;
    right: 30px;
    top: 6px;
    cursor: pointer;
    display: none;
  }
  &:hover {
    .del,
    .show-big {
      display: inline-block;
    }
  }
}
</style>
